import React, { useState } from 'react';
import axios from 'axios';
import { useLocation, useNavigate } from "react-router-dom";



// 模拟周易运势算法
const calculateFortune = (userData) => {

  // 生成八字（简化版）
  const birthDate = new Date(userData.出生日期);
  const stems = ['甲','乙','丙','丁','戊','己','庚','辛','壬','癸'];
  const branches = ['子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥'];
  
  // 生成卦象
  const hexagrams = ['乾为天', '坤为地', '水雷屯', '山水蒙', '水天需', '天水讼'];
  const randomHexagram = hexagrams[Math.floor(Math.random() * hexagrams.length)];

  // 运势组合逻辑
  return {
    八字: `${stems[birthDate.getFullYear() % 10]}${branches[birthDate.getMonth() % 12]}`,
    卦象: randomHexagram,
    健康指数: Math.floor(Math.random() * 5) + 1,
    事业指数: Math.floor(Math.random() * 5) + 1,
    财运指数: Math.floor(Math.random() * 5) + 1,
    幸运颜色: ['金','木','水','火','土'][Math.floor(Math.random() * 5)],
    今日宜: ['签约','出行','学习','投资','合作'][Math.floor(Math.random() * 5)],
    今日忌: ['借贷','争吵','搬家','冒险','决策'][Math.floor(Math.random() * 5)]
  };
};

export default function ZouYi() {
  const navigate = useNavigate();
 

  
  const [formData, setFormData] = useState({
    name: '',
    gender: '',
    birthYear: '',
    birthMonth: '',
    birthDay: '',
    birthHour: ''
  });
  console.log(formData)
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState('');
  const [error, setError] = useState('');
  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };
  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    setResult('');
    try {
      const response = await axios.post('http://localhost:5000/api/asksse', formData);
      setResult(response.data.answer);
    } catch (err) {
      setError(err.response?.data?.error || err.response?.data?.details || '请求失败，请稍后重试');
      console.error('API请求错误:', err);
    } finally {
      setLoading(false);
    }
  };
  const genderOptions = [
    { label: '男', value: '男' },
    { label: '女', value: '女' }
  ];
  const hourOptions = Array.from({ length: 24 }, (_, i) => ({
    label: `${i.toString().padStart(2, '0')}:00`,
    value: `${i.toString().padStart(2, '0')}:00`
  }));

  const TioaZhuan = () => {
    // 点击按钮时携带 formData 跳转到子组件路由
    navigate('/ljwsc', { state: { formData,result } });
  };
  const a=0
///
//  const [formData, setFormData] = useState({
//         姓名: '',
//         性别: '',
//         出生日期: ''
//       });
//       console.log(formData)
//       const [fortune, setFortune] = useState(null);
//       const [loading, setLoading] = useState(false);
    
      const handleSubmitss = () => {
        if (!formData.姓名 || !formData.性别 || !formData.出生日期) {
          alert('请填写完整信息');
          return;
        }
        
        setLoading(true);
        setTimeout(() => {
          setFortune(calculateFortune(formData));
          setLoading(false);
        }, 1500);
      };
    
      // 生成星级显示
      const renderStars = (num) => '★'.repeat(num) + '☆'.repeat(5 - num);

      const geshi=result.replace(/[^\u4e00-\u9fa5 .0-9a-zA-Z\n]/g, '');


  return (
    <div className="fortune-container" >
      

      <div style={{width:'50%',marginLeft:'25%',height:'300px',textAlign:'center',overflow:'hidden',border:' 3px solid orange',backgroundSize: '100% auto', backgroundImage:'url(../img/ljwyao1.png)',color:'wheat'}}>
      <form onSubmit={handleSubmit}>
      {/* 姓名 */}
      <div className="form-group" style={{marginTop:'80px',color:'rgb(255, 255, 255)'}}>
        <label>
          姓名:
          <input
            type="text"
            name="name"
            value={formData.name}
            onChange={handleChange}
            required
            style={{width:'200px',height:'30px',border:' 3px solid orange',color:'black',borderRadius:'15px'}}
          />
        </label>
      </div>
      {/* 性别 */}
      <div className="form-group" style={{color:"rgb(255, 255, 255)"}}>
        <label>
          性别:
          <select
            name="gender"
            value={formData.gender}
            onChange={handleChange}
            required
            style={{width:'200px',height:'30px',border:' 3px solid orange',color:'black',borderRadius:'15px'}}
          >
            <option value="">请选择性别</option>
            {genderOptions.map(option => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </label>
      </div>
      {/* 出生年月日 */}
      <div className="form-row">
        <div className="form-group" style={{color:"rgb(255, 255, 255)"}}>
          <label>
            出生年份:
            <input
              type="number"
              name="birthYear"
              value={formData.birthYear}
              onChange={handleChange}
              min="1900"
              max={new Date().getFullYear()}
              placeholder="如1990"
              required
              style={{width:'200px',height:'30px',border:' 3px solid orange',color:'black',borderRadius:'15px'}}
            />
          </label>
        </div>
        <div className="form-group" style={{color:"rgb(255, 255, 255)"}}>
          <label>
            出生月份:
            <input
              type="number"
              name="birthMonth"
              value={formData.birthMonth}
              onChange={handleChange}
              min="1"
              max="12"
              placeholder="1-12"
              required
              style={{width:'200px',height:'30px',border:' 3px solid orange',color:'black',borderRadius:'15px'}}
            />
          </label>
        </div>
        <div className="form-group" style={{color:"rgb(255, 255, 255)"}}>
          <label>
            出生日期:
            <input
              type="number"
              name="birthDay"
              value={formData.birthDay}
              onChange={handleChange}
              min="1"
              max="31"
              placeholder="1-31"
              required
              style={{width:'200px',height:'30px',border:' 3px solid orange',color:'black',borderRadius:'15px'}}
            />
          </label>
        </div>
      </div>
      {/* 出生时辰 */}
      <div className="form-group" style={{color:"rgb(255, 255, 255)"}}>
        <label>
          出生时辰(可选):
          <select
            name="birthHour"
            value={formData.birthHour}
            onChange={handleChange}
            style={{width:'200px',height:'30px',border:' 3px solid orange',color:'black',borderRadius:'15px'}}
          >
            <option value="">不确定</option>
            {hourOptions.map(option => (
              <option key={option.value} value={option.value}>
                {option.label}
              </option>
            ))}
          </select>
        </label>
      </div>

      <button type="submit" disabled={loading} style={{width:'150px',height:'30px',border:' 3px solid orange',color:'black',borderRadius:'15px',fontFamily:'隶书',}} >
        {loading ? '测算中...' : '六爻测算运势'}
      </button>

    </form>
      </div>

    <div style={{width:'50%',marginLeft:'25%',backgroundSize: '100% auto', backgroundImage:'url(../img/beiban.png)',color:'rgb(255, 255, 255)',overflow:'hidden' ,fontSize:'20px'}}>


    {error && <div className="error-message">{error}</div>}
        {result && (
      <div className="result-container">
        <h3>2025年运势分析结果:</h3>
        <div className="result-content">
          {/* 保留原有换行格式 */}
          {geshi.split('\n').map((paragraph, index) => (
            <p key={index}>{paragraph}</p>
          ))}
        </div>
      </div>
    )}
    
    </div>

    
  </div>
  )
}


///////
  ////样式
  const cardStyle = {
    padding: '15px',
    background: '#fff',
    borderRadius: '8px',
    boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
    // textAlign: 'center'
  };
  
  const labelStyle = {
    color: '#666',
    fontSize: '14px',
    marginBottom: '8px'
  };
  
  const adviceStyle = {
    flex: 1,
    padding: '15px',
    border: '2px solid',
    borderRadius: '8px',
    position: 'relative',
    textAlign: 'center'
  };
  
  const badgeStyle = {
    position: 'absolute',
    top: '-12px',
    left: '50%',
    transform: 'translateX(-50%)',
    color: '#fff',
    padding: '4px 12px',
    borderRadius: '20px',
    fontSize: '14px'
  };